package org.hilo.boot.app.config;

import java.net.UnknownHostException;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.hilo.boot.core.redis.JedisConnectionConfiguration;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.JedisClientConfigurationBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

import redis.clients.jedis.Jedis;

/**
 * 
 * @author zollty
 * @since 2022年8月23日
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ GenericObjectPool.class, JedisConnection.class, Jedis.class })
@ConditionalOnProperty(name = "hilo.enable-default-redis", havingValue = "true", matchIfMissing = true)
@ConditionalOnMissingBean(name = "redisConnectionFactory")
public class DefaultJedisConnectionFactory {

    @Primary
    @Bean
    public JedisConnectionFactory redisConnectionFactory(
            @Qualifier("redisProperties") RedisProperties properties,
            ObjectProvider<RedisSentinelConfiguration> sentinelConfiguration,
            ObjectProvider<RedisClusterConfiguration> clusterConfiguration,
            ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers)
            throws UnknownHostException {
        return new JedisConnectionConfiguration(properties, sentinelConfiguration,
                clusterConfiguration, builderCustomizers).redisConnectionFactory();
    }
}
